package edu.ntu.helper;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import edu.ntu.helper.RestClient.RequestMethod;
import edu.ntu.mobilestomp.R;

public class UploadTask extends AsyncTask<String, Integer, String> {

	private Context mContext;
	private String existingFileName = "";
    
    private NotificationHelper mNotificationHelper;
    
    public UploadTask(Context context){
    	mContext = context;
    	mNotificationHelper = new NotificationHelper(context);
    }

    protected void onPreExecute(){
        //Create the notification in the statusbar
        mNotificationHelper.createNotification();
    }
    
	@Override
	protected String doInBackground(String... filepaths) {
		int count = filepaths.length;
		
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        
        for (int i = 0; i < count; i++) {
            existingFileName = filepaths[i];
        }
        
        //String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mypic.png";
        //Log.v("TEST",Environment.getExternalStorageDirectory().getAbsolutePath() + "/mypic.png");
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary =  "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;
        String responseFromServer = "";
        String urlString = mContext.getString(R.string.base_url)+"/upload.php";
        
        try
        {
	         //------------------ CLIENT REQUEST
	        FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
	         // open a URL connection to the Servlet
	         URL url = new URL(urlString);
	         // Open a HTTP connection to the URL
	         conn = (HttpURLConnection) url.openConnection();
	         // Allow Inputs
	         conn.setDoInput(true);
	         // Allow Outputs
	         conn.setDoOutput(true);
	         // Don't use a cached copy.
	         conn.setUseCaches(false);
	         // Use a post method.
	         conn.setRequestMethod("POST");
	         conn.setRequestProperty("Connection", "Keep-Alive");
	         conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
	         dos = new DataOutputStream( conn.getOutputStream() );
	         dos.writeBytes(twoHyphens + boundary + lineEnd);
	         dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
	         dos.writeBytes(lineEnd);
	         // create a buffer of maximum size
	         bytesAvailable = fileInputStream.available();
	         bufferSize = Math.min(bytesAvailable, maxBufferSize);
	         buffer = new byte[bufferSize];
	         // read file and write it into form...
	         bytesRead = fileInputStream.read(buffer, 0, bufferSize);
	         while (bytesRead > 0)
	         {
				dos.write(buffer, 0, bufferSize);
				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
	         }
	         // send multipart form data necesssary after file data...
	         dos.writeBytes(lineEnd);
	         dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
	         // close streams
	         Log.e("Debug","File is written");
	         fileInputStream.close();
	         dos.flush();
	         dos.close();
        }
        catch (MalformedURLException ex)
        {
             Log.e("Debug", "error: " + ex.getMessage(), ex);
        }
        catch (IOException ioe)
        {
             Log.e("Debug", "error: " + ioe.getMessage(), ioe);
        }
        //------------------ read the SERVER RESPONSE
        try {
              inStream = new DataInputStream ( conn.getInputStream() );
              String str;
             
              while (( str = inStream.readLine()) != null)
              {
                   Log.e("Debug","Server Response "+str);
              }
              inStream.close();

        }
        catch (IOException ioex){
             Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        }
		return "DONE";
	}
	
	// Code to update progress
    protected void onProgressUpdate(Integer... progress) {
        //This method runs on the UI thread, it receives progress updates
        //from the background thread and publishes them to the status bar
        mNotificationHelper.progressUpdate(progress[0]);
    }

    // Code when upload is success
    protected void onPostExecute(String result) {
        //showDialog("Downloaded " + result + " bytes");
    	Log.v("debug","creating thumbnails"+existingFileName);
    	
    	String[] items = existingFileName.split("/"); 
    	String filename = items[items.length-1];
    	
    	//Creating thumbnails
    	RestClient client = new RestClient(mContext.getString(R.string.base_url) + "/mk_thumbnail.php");
		client.AddParam("filename", filename);
		
		try {
		    client.Execute(RequestMethod.POST);
		} catch (Exception e) {
		    e.printStackTrace();
		}
		
        //The task is complete, tell the status bar about it
        mNotificationHelper.completed();
    }
	
	

}
